package com.example.take_out_file.service.impl;

import com.example.take_out_file.config.QiniuConfig;
import com.example.take_out_file.model.vo.FileVO;
import com.example.take_out_file.service.FileService;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private QiniuConfig qiniuConfig;

    @Override
    public String upload(MultipartFile file) {
        if (file == null) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }

        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件为空");
        }


        try {
            // 获取file的地址
            String originalFilename = file.getOriginalFilename();
            //file扩展名 extendFileName
            String extendFileName = originalFilename.substring(originalFilename.lastIndexOf("."));

            log.info("fileAddress: {}", originalFilename);
            log.info("fileExtend: {}", extendFileName);
            // 构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration(Zone.huadong()); // 使用默认区域 Zone.zone0() 或根据实际情况选择其他区域

            // 从 MultipartFile 直接获取输入流，避免先保存到本地再上传
            InputStream inputStream = file.getInputStream();

            log.info("inputStream: {}", inputStream);
            // 默认不指定key的情况下，以文件内容的hash值作为文件名 时间日期前缀
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd/");
            // 获取当前日期
            String key = currentDate.format(formatter) + UUID.randomUUID().toString().replace("-", "") + extendFileName;

            Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            String upToken = auth.uploadToken(qiniuConfig.getBucket());

            try (InputStream ignored = inputStream) {
                UploadManager uploadManager = new UploadManager(cfg);
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                FileVO fileVO = new FileVO();
                fileVO.setUrl(qiniuConfig.getPrefixUrl() + putRet.key);
                log.info("fileUrl:{}",fileVO);
                return fileVO.getUrl();
            } catch (IOException ex) {
                log.error("Failed to upload file: {}", originalFilename, ex);
                return null;
            }
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return null;
        }

    }
}
